<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>


<script data-ad-client="ca-pub-8048531516491146" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

  <meta name="description" content="iOS系统是出了名的封闭，每个应用的活动范围被严格地限制在各自的沙盒中。尽管如此，iOS还是提供了若干进程间通信机制，CFMessagePort就是其中之一。 从类名可以看出，CFMessagePort属于Core Foundation层的东西，其实现部分是开源的，代码在可以在苹果的开源代码库中找到。 使用方式1、消息接收者CFMessagePort端口消息的接收者需要实现以下功能： 1.1 注册">
<meta name="keywords" content="iOS, 进程通信, CFMessagePort">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS进程间通信之CFMessagePort">
<meta property="og:url" content="http://foogry.org/2014/06/04/2014-06-04-iosjin-cheng-jian-tong-xin-zhi-cfmessageport/index.html">
<meta property="og:site_name" content="foogry的技术博客">
<meta property="og:description" content="iOS系统是出了名的封闭，每个应用的活动范围被严格地限制在各自的沙盒中。尽管如此，iOS还是提供了若干进程间通信机制，CFMessagePort就是其中之一。 从类名可以看出，CFMessagePort属于Core Foundation层的东西，其实现部分是开源的，代码在可以在苹果的开源代码库中找到。 使用方式1、消息接收者CFMessagePort端口消息的接收者需要实现以下功能： 1.1 注册">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-09-24T12:14:54.775Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iOS进程间通信之CFMessagePort">
<meta name="twitter:description" content="iOS系统是出了名的封闭，每个应用的活动范围被严格地限制在各自的沙盒中。尽管如此，iOS还是提供了若干进程间通信机制，CFMessagePort就是其中之一。 从类名可以看出，CFMessagePort属于Core Foundation层的东西，其实现部分是开源的，代码在可以在苹果的开源代码库中找到。 使用方式1、消息接收者CFMessagePort端口消息的接收者需要实现以下功能： 1.1 注册">
  <link rel="canonical" href="http://foogry.org/2014/06/04/2014-06-04-iosjin-cheng-jian-tong-xin-zhi-cfmessageport/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>iOS进程间通信之CFMessagePort | foogry的技术博客</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?2944231de73b405a5da5c6b4097cfa0e";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">foogry的技术博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">Stay hungry,stay foolish.</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="http://foogry.org/2014/06/04/2014-06-04-iosjin-cheng-jian-tong-xin-zhi-cfmessageport/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="foogry">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="foogry的技术博客">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">iOS进程间通信之CFMessagePort

          
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2014-06-04 18:31:51" itemprop="dateCreated datePublished" datetime="2014-06-04T18:31:51+08:00">2014-06-04</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-09-24 20:14:54" itemprop="dateModified" datetime="2019-09-24T20:14:54+08:00">2019-09-24</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a></span>

                
                
              
            </span>
          

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
        
      
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2014/06/04/2014-06-04-iosjin-cheng-jian-tong-xin-zhi-cfmessageport/#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/2014/06/04/2014-06-04-iosjin-cheng-jian-tong-xin-zhi-cfmessageport/" itemprop="commentCount"></span></a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>iOS系统是出了名的封闭，每个应用的活动范围被严格地限制在各自的沙盒中。尽管如此，iOS还是提供了若干进程间通信机制，CFMessagePort就是其中之一。</p>
<p>从类名可以看出，CFMessagePort属于<code>Core Foundation</code>层的东西，其实现部分是开源的，代码在可以在苹果的<a href="http://opensource.apple.com/source/CF/CF-855.14/CFMessagePort.c" target="_blank" rel="noopener">开源代码库</a>中找到。</p>
<h2 id="使用方式"><a href="#使用方式" class="headerlink" title="使用方式"></a>使用方式</h2><h4 id="1、消息接收者"><a href="#1、消息接收者" class="headerlink" title="1、消息接收者"></a>1、消息接收者</h4><p>CFMessagePort端口消息的接收者需要实现以下功能：</p>
<h6 id="1-1-注册监听"><a href="#1-1-注册监听" class="headerlink" title="1.1 注册监听"></a>1.1 注册监听</h6><p>消息接收者需要通过以下方式注册消息监听：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">-(void)startListenning</span><br><span class="line">&#123;</span><br><span class="line">	if (0 != mMsgPortListenner &amp;&amp; CFMessagePortIsValid(mMsgPortListenner))</span><br><span class="line">	&#123;</span><br><span class="line">		CFMessagePortInvalidate(mMsgPortListenner);</span><br><span class="line">	&#125;</span><br><span class="line">    mMsgPortListenner = CFMessagePortCreateLocal(kCFAllocatorDefault,CFSTR(LOCAL_MACH_PORT_NAME),onRecvMessageCallBack, NULL, NULL);</span><br><span class="line">    CFRunLoopSourceRef source = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, mMsgPortListenner, 0);</span><br><span class="line">    CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);</span><br><span class="line">    NSLog(@&quot;start listenning&quot;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

 <a id="more"></a>



<p>其中<code>LOCAL_MACH_PORT_NAME</code>的定义为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">#define LOCAL_MACH_PORT_NAME    &quot;com.wangzz.demo&quot;</span><br></pre></td></tr></table></figure>

<p>经过查看源码发现，CFMessagePort实际上是通过mach port实现的。Mach port是iOS系统提供的基于端口的输入源，可用于线程或进程间通讯。而Runloop支持的输入源类型中就包括基于端口的输入源，因此可以使用Runloop做为CFMessagePort端口源事件的监听者。</p>
<p>上述代码有几点需要说明：</p>
<ul>
<li><p>通过CFMessagePortCreateLocal可以创建一个本地CFMessagePortRef对象</p>
</li>
<li><p>CFMessagePort对象是靠一个字符串来唯一标识的，这一点非常重要，在这里字符串是由宏<code>LOCAL_MACH_PORT_NAME</code>定义的；</p>
</li>
<li><p>创建CFMessagePort对象的同时设置了端口源事件的回调函数onRecvMessageCallBack，用于处理端口源事件；</p>
</li>
<li><p>将创建的对象作为输入源添加到Runloop中，从而实现对端口源事件的监听，当Runloop收到对应的端口源事件时，会调用上一步中指定的回调芳芳；</p>
</li>
</ul>
<h6 id="1-2-实现回调方法"><a href="#1-2-实现回调方法" class="headerlink" title="1.2 实现回调方法"></a>1.2 实现回调方法</h6><p>回调函数为CFMessagePortCallBack类型，其定义部分为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">typedef CFDataRef (*CFMessagePortCallBack) (</span><br><span class="line">   CFMessagePortRef local,</span><br><span class="line">   SInt32 msgid,</span><br><span class="line">   CFDataRef data,</span><br><span class="line">   void *info</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<p>各个参数的含义为：</p>
<ul>
<li><p>CFMessagePortRef local</p>
<p>  当前接收消息的CFMessagePortRef对象。</p>
</li>
<li><p>SInt32 msgid</p>
<p>  这个字段非常有用，用于标识消息。如果通信双方进程约定号每个msgid对应的数据结构，即可实现较为复杂的通信。</p>
</li>
<li><p>CFDataRef data</p>
<p>  通信的真正数据部分。</p>
</li>
<li><p>void *info</p>
<p>  为使用CFMessagePortCreateLocal方法创建port端口时指定的CFMessagePortContext对象的info字段，通常为空。</p>
</li>
</ul>
<p>该回调方法可以返回一个CFDataRef类型的数据给port消息的发送者，以实现有效的双方通信，这一点也非常重要。</p>
<p>我的回调函数onRecvMessageCallBack的实现：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">CFDataRef onRecvMessageCallBack(CFMessagePortRef local,SInt32 msgid,CFDataRef cfData, void*info)</span><br><span class="line">&#123;</span><br><span class="line">    NSLog(@&quot;onRecvMessageCallBack is called&quot;);</span><br><span class="line">    NSString *strData = nil;</span><br><span class="line">    if (cfData)</span><br><span class="line">    &#123;</span><br><span class="line">       	const UInt8  * recvedMsg = CFDataGetBytePtr(cfData);</span><br><span class="line">    	strData = [NSString stringWithCString:(char *)recvedMsg encoding:NSUTF8StringEncoding];</span><br><span class="line">        /**</span><br><span class="line">         </span><br><span class="line">         实现数据解析操作</span><br><span class="line">         </span><br><span class="line">         **/</span><br><span class="line">        </span><br><span class="line">        NSLog(@&quot;receive message:%@&quot;,strData);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    //为了测试，生成返回数据</span><br><span class="line">    NSString *returnString = [NSString stringWithFormat:@&quot;i have receive:%@&quot;,strData];</span><br><span class="line">    const char* cStr = [returnString UTF8String];</span><br><span class="line">	NSUInteger ulen = [returnString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];</span><br><span class="line">    CFDataRef sgReturn = CFDataCreate(NULL, (UInt8 *)cStr, ulen);</span><br><span class="line">    </span><br><span class="line">    return sgReturn;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该方法实现的较为简单，解析约定的数据（测试代码中约定传送的是string）,为了测试，同时生成一个CFDataRef数据返回给port消息的发送者。</p>
<h6 id="1-3-取消端口监听"><a href="#1-3-取消端口监听" class="headerlink" title="1.3 取消端口监听"></a>1.3 取消端口监听</h6><p>可以通过如下方式取消对port端口的监听：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- (void)endLisenning</span><br><span class="line">&#123;</span><br><span class="line">    CFMessagePortInvalidate(mMsgPortListenner);</span><br><span class="line">    CFRelease(mMsgPortListenner);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>CFMessagePortInvalidate会停止port消息的发送和接收操作，而只有调用了CFRelease，CFMessagePortRef对象才真正的被释放掉。</p>
<h4 id="2、消息发送者"><a href="#2、消息发送者" class="headerlink" title="2、消息发送者"></a>2、消息发送者</h4><p>发送部分代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">-(NSString *)sendMessageToDameonWith:(id)msgInfo msgID:(NSInteger)msgid</span><br><span class="line">&#123;</span><br><span class="line">    // 生成Remote port</span><br><span class="line">    CFMessagePortRef bRemote = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR(MACH_PORT_REMOTE));</span><br><span class="line">    if (nil == bRemote) &#123;</span><br><span class="line">        NSLog(@&quot;bRemote create failed&quot;);</span><br><span class="line">        return nil;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    // 构建发送数据（string）</span><br><span class="line">    NSString    *msg = [NSString stringWithFormat:@&quot;%@&quot;,msgInfo];</span><br><span class="line">    NSLog(@&quot;send msg is :%@&quot;,msg);</span><br><span class="line">    const char *message = [msg UTF8String];</span><br><span class="line">    CFDataRef data,recvData = nil;</span><br><span class="line">    data = CFDataCreate(NULL, (UInt8 *)message, strlen(message));</span><br><span class="line">    </span><br><span class="line">    // 执行发送操作</span><br><span class="line">    CFMessagePortSendRequest(bRemote, msgid, data, 0, 100 , kCFRunLoopDefaultMode, &amp;recvData);</span><br><span class="line">    if (nil == recvData) &#123;</span><br><span class="line">        NSLog(@&quot;recvData date is nil.&quot;);</span><br><span class="line">        CFRelease(data);</span><br><span class="line">        CFMessagePortInvalidate(bRemote);</span><br><span class="line">        CFRelease(bRemote);</span><br><span class="line">        return nil;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    // 解析返回数据</span><br><span class="line">    const UInt8  * recvedMsg = CFDataGetBytePtr(recvData);</span><br><span class="line">    if (nil == recvedMsg) &#123;</span><br><span class="line">        NSLog(@&quot;receive date err.&quot;);</span><br><span class="line">        CFRelease(data);</span><br><span class="line">        CFMessagePortInvalidate(bRemote);</span><br><span class="line">        CFRelease(bRemote);</span><br><span class="line">        return nil;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    NSString    *strMsg = [NSString stringWithCString:(char *)recvedMsg encoding:NSUTF8StringEncoding];</span><br><span class="line">    NSLog(@&quot;%@&quot;,strMsg);</span><br><span class="line">    </span><br><span class="line">    CFRelease(data);</span><br><span class="line">    CFMessagePortInvalidate(bRemote);</span><br><span class="line">    CFRelease(bRemote);</span><br><span class="line">    CFRelease(recvData);</span><br><span class="line">    </span><br><span class="line">    return strMsg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中<code>MACH_PORT_REMOTE</code>的定义为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">#define MACH_PORT_REMOTE    &quot;com.wangzz.demo&quot;</span><br></pre></td></tr></table></figure>

<p>发送消息时要相对简单，首先通过CFMessagePortCreateRemote生成一个Remote的CFMessagePortRef，这里需要注意的是CFMessagePortCreateRemote时传入的字符串唯一标识<code>MACH_PORT_REMOTE</code>必须和消息接收者创建local的CFMessagePortRef时使用的字符串唯一标识是同一个！</p>
<p>通过查看源码发现，CFMessagePortCreateRemote会根据<code>MACH_PORT_REMOTE</code>定义的字符串为唯一标识获取消息接收者通过CFMessagePortCreateLocal使用相同字符串创建的底层mach port端口，从而实现向消息接收者发送信息。</p>
<p>如果消息接收者还没有创建或者通过CFMessagePortCreateLocal创建local端口失败时，想要通过CFMessagePortCreateRemote去创建remote端口肯定是失败的。</p>
<h2 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明</h2><ul>
<li>很遗憾的是，在iOS7及以后系统中，CFMessagePort的通信机制不再可用。</li>
</ul>
<p>在使用CFMessagePortCreateLocal/CFMessagePortCreateRemote创建CFMessagePortRef对象时会失败，官方文档中是这么说的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">This method is not available on iOS 7 and later—it will return NULL and log a sandbox violation in syslog. See Concurrency Programming Guide for possible replacement technologies.</span><br></pre></td></tr></table></figure>

<ul>
<li><p>CFMessagePort只能用于本地进程通信。</p>
</li>
<li><p>CFMessagePort是基于mach port端口的通信方式，不但可以用于进程通信，也可以用于线程间通信，只是线程间通信有了GCD和Cocoa提供的原生方法，已经能很方便的实现了，没必要再使用CFMessagePort。</p>
</li>
<li><p>进程通信使用场景</p>
</li>
</ul>
<p>iOS系统多任务机制，使得进程间通信基本都只能用于越狱开发。常用的场景是前端有一个UI程序用于界面展示，后端有一个daemo精灵程序用于任务处理。</p>
<h2 id="demo工程"><a href="#demo工程" class="headerlink" title="demo工程"></a>demo工程</h2><p>特地做了了个demo工程，以便更好地演示CFMessagePort的使用，可以到<a href="http://download.csdn.net/detail/wzzvictory_tjsd/7446745" target="_blank" rel="noopener">CSDN下载</a>。</p>
<p>为了模拟进程间通信场景，我将消息接收进程CFMessagePortReceive做成了能够后台播放音乐的程序，以便其切到后台后能继续存活。</p>
<p>由于CFMessagePort不再支持iOS7及以后系统，本demo实在iOS6系统上测试的。</p>
<p>demo使用方式：</p>
<ul>
<li><p>CFMessagePortReceive启动后，点击Start Listenning创建CFMessagePort接口并开始监听port消息，然后将CFMessagePortReceive切到后台；</p>
</li>
<li><p>启动CFMessagePortSend程序，在输入框中写入内容，点击发送按钮即可和CFMessagePortReceive通信。</p>
</li>
<li><p>MessagePort通信过程中会有日志输出，可以使用以下方式查看日志：</p>
<p>  1.真机</p>
<p>  选择：Xcode-&gt;Window-&gt;Organizer-&gt;Devices，然后选中窗口左侧当前设备的Console窗口查看。</p>
<p>  2.模拟器</p>
<p>  选择：模拟器-&gt;调试-&gt;打开系统日志，或者直接使用快捷键<code>⌘/</code>直接打开系统控制台查看日志。</p>
</li>
</ul>
<h2 id="参考文档"><a href="#参考文档" class="headerlink" title="参考文档"></a>参考文档</h2><ul>
<li><p><a href="http://opensource.apple.com/source/CF/CF-855.14/" target="_blank" rel="noopener">CF-855.14</a></p>
</li>
<li><p><a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW1" target="_blank" rel="noopener">Threading Programming Guide</a></p>
</li>
<li><p><a href="https://developer.apple.com/library/mac/documentation/corefoundation/Reference/CFMessagePortRef/Reference/reference.html#//apple_ref/doc/uid/20001437-CH203-DontLinkElementID_8" target="_blank" rel="noopener">CFMessagePort Reference</a></p>
</li>
</ul>

    </div>

    
    
    
        
      
        <div id="reward-container">
  <div></div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
        
      
      <div style="display: inline-block">
        <img src="/images/weixinpay.jpg" alt="foogry 微信支付">
        <p>微信支付</p>
      </div>

  </div>
</div>

      
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>foogry</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://foogry.org/2014/06/04/2014-06-04-iosjin-cheng-jian-tong-xin-zhi-cfmessageport/" title="iOS进程间通信之CFMessagePort">http://foogry.org/2014/06/04/2014-06-04-iosjin-cheng-jian-tong-xin-zhi-cfmessageport/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/deed.zh" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-ND</a> 许可协议。转载请注明出处！</li>
</ul>
</div>

      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/iOS/" rel="tag"># iOS</a>
            
              <a href="/tags/进程通信/" rel="tag"># 进程通信</a>
            
              <a href="/tags/CFMessagePort/" rel="tag"># CFMessagePort</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2014/05/25/2014-05-25-iosmo-ni-qi-custom-locationbei-zhong-zhi-jie-jue-fang-an/" rel="next" title="iOS模拟器Custom Location被重置解决方案">
                  <i class="fa fa-chevron-left"></i> iOS模拟器Custom Location被重置解决方案
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2014/06/12/2014-06-12-wwdc2014zhi-iosshi-yong-dong-tai-ku/" rel="prev" title="WWDC2014之iOS使用动态库">
                  WWDC2014之iOS使用动态库 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    <div class="comments" id="comments"></div>
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用方式"><span class="nav-number">1.</span> <span class="nav-text">使用方式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、消息接收者"><span class="nav-number">1.0.1.</span> <span class="nav-text">1、消息接收者</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#1-1-注册监听"><span class="nav-number">1.0.1.0.1.</span> <span class="nav-text">1.1 注册监听</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#1-2-实现回调方法"><span class="nav-number">1.0.1.0.2.</span> <span class="nav-text">1.2 实现回调方法</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#1-3-取消端口监听"><span class="nav-number">1.0.1.0.3.</span> <span class="nav-text">1.3 取消端口监听</span></a></li></ol></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2、消息发送者"><span class="nav-number">1.0.2.</span> <span class="nav-text">2、消息发送者</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#说明"><span class="nav-number">2.</span> <span class="nav-text">说明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#demo工程"><span class="nav-number">3.</span> <span class="nav-text">demo工程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考文档"><span class="nav-number">4.</span> <span class="nav-text">参考文档</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">foogry</p>
  <div class="site-description" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">22</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span>
        
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
        <span class="site-state-item-count">56</span>
        <span class="site-state-item-name">标签</span>
        
      </div>
    
  </nav>
  <div class="cc-license motion-element" itemprop="license">
    
  
    <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-nd.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">foogry</span>
</div>
  <div class="powered-by">Hosted by <a href="https://coding.net/pages" class="theme-link" rel="noopener" target="_blank">Coding Pages</a></div>
  <span class="post-meta-divider">|</span>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.4.0</div>

        












        
      </div>
    </footer>
  </div>

  


  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>
<script src="/js/next-boot.js?v=7.4.0"></script>



  





















  

  

  


<script>
NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(item => {
    return GUEST.includes(item);
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'vqsvFaA8FXndr4867HJvtJ7P-gzGzoHsz',
    appKey: '6L6ddsrLCJVMetc2W7CL9kkf',
    placeholder: 'Comment Here',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: 'zh-cn' || 'zh-cn',
    path: location.pathname
  });
}, window.Valine);
</script>

</body>
</html>
